package com.bootdo.system.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.bootdo.common.utils.*;
import com.bootdo.system.domain.*;
import com.bootdo.system.service.*;
import com.bootdo.system.vo.BaojiaVo;
import com.bootdo.system.vo.BaojiaVoForSonsys;
import com.bootdo.system.vo.ProjectVo;
import com.bootdo.system.vo.SonsysVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.web.config.ProjectingArgumentResolverRegistrar;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 子系统表
 *
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2020-06-26 09:33:29
 */

@Controller
@RequestMapping("/system/sonsys")
public class SonsysController {
    @Autowired
    private SonsysService sonsysService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProductInnerService productInnerService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductInnerController productInnerController;


    @RequestMapping("/downExcel/{sonsysId}")
    @RequiresPermissions("system:sonsys:downExcel")
    public void downExcel(@PathVariable("sonsysId") Integer sonsysId, HttpServletResponse response) {

        downExcelBasic(sonsysId, response);

    }

    public void downExcelBasic(Integer sonsysId, HttpServletResponse response) {
        //下载excel
        SonsysDO sonsysDO = sonsysService.get(sonsysId);

        List<ProductInnerDO> list = productInnerService.getProDuctBysonsysId(sonsysId);

        List<ProjectVo> alllist = getVoBydo(list);

        try {
            writeExcel(response, alllist, sonsysDO);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/downExcel2/{sonsysId}")
    @RequiresPermissions("system:sonsys:downExcel2")
    public void downExcel2(@PathVariable("sonsysId") Integer sonsysId, HttpServletResponse response) {

        SonsysDO sonsysDO = sonsysService.get(sonsysId);

        List<ProductInnerDO> list = productInnerService.getProDuctBysonsysId(sonsysId);

        List<BaojiaVoForSonsys> baojiaVoForSonsys = getBaojiaVoBydo(list);

        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义标题别名
        writer.addHeaderAlias("productNum", "产品编号");
        writer.addHeaderAlias("shebeiName", "产品名称");

        writer.addHeaderAlias("categoryName", "产品分类");
        writer.addHeaderAlias("baseParam", "基本参数");
        writer.addHeaderAlias("allParam", "完整参数");
        writer.addHeaderAlias("unit", "单位");
        writer.addHeaderAlias("brand", "品牌");
        writer.addHeaderAlias("xinghao", "型号");


        writer.addHeaderAlias("baojia", "报价");
        writer.addHeaderAlias("zhekou", "折扣");
        writer.addHeaderAlias("shijibaojia", "实际报价");
        writer.addHeaderAlias("proNum", "数量");
        writer.addHeaderAlias("allbaojia", "总报价");
        writer.addHeaderAlias("beizhu", "备注");


        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(13, sonsysDO.getProjectDO().getProjectNum() + "." + sonsysDO.getProjectDO().getProjectName()
                + " - " + sonsysDO.getSonsysName() +
                "  子系统报价：" + MyUtils.getAlldouble(sonsysDO.getSonbaojia()));
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(baojiaVoForSonsys, true);
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        String name = sonsysDO.getSonsysName();

        try {
            name = new String(name.getBytes("GBK"), "ISO8859_1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer，释放内存
            writer.close();
        }
        //此处记得关闭输出Servlet流
        IoUtil.close(out);

    }

    private List<BaojiaVoForSonsys> getBaojiaVoBydo(List<ProductInnerDO> list) {
        ArrayList<BaojiaVoForSonsys> baojiaVos = new ArrayList<>();

        for (ProductInnerDO productInnerDO : list) {
            BaojiaVoForSonsys baojiaVo = new BaojiaVoForSonsys();
            baojiaVo.setAllbaojia(productInnerDO.getAllbaojia());
            baojiaVo.setBaojia(productInnerDO.getBaojia());
            baojiaVo.setBeizhu(productInnerDO.getBeizhu());
            baojiaVo.setProNum(productInnerDO.getProNum());
            ProductDO productDO = productService.get(productInnerDO.getProductId());
            BeanUtils.copyProperties(productDO, baojiaVo);
            baojiaVo.setZhekou(productInnerDO.getZhekou());
            baojiaVo.setShijibaojia(productInnerDO.getShijibaojia());

            CategoryDO categoryDO = categoryService.get(productDO.getCategoryId());
            baojiaVo.setCategoryName(categoryDO.getCategoryName());
            baojiaVo.setShebeiName(productDO.getShebeiName());
            baojiaVo.setCategoryName(categoryDO.getCategoryName());
            baojiaVos.add(baojiaVo);
        }

        return baojiaVos;
    }

    public void writeExcel(HttpServletResponse response, List<ProjectVo> list, SonsysDO sonsysDO) throws UnsupportedEncodingException {

        // 通过工具类创建writer，默认创建xls格式
        ExcelWriter writer = ExcelUtil.getWriter();
        //自定义标题别名
        writer.addHeaderAlias("productNum", "产品编号");
        writer.addHeaderAlias("shebeiName", "产品名称");

        writer.addHeaderAlias("categoryName", "产品分类");
        writer.addHeaderAlias("baseParam", "基本参数");
        writer.addHeaderAlias("allParam", "完整参数");
        writer.addHeaderAlias("unit", "单位");
        writer.addHeaderAlias("brand", "品牌");
        writer.addHeaderAlias("xinghao", "型号");


        writer.addHeaderAlias("sonsysName", "子系统名字");
        writer.addHeaderAlias("anzhuangChengben", "安装成本");
        writer.addHeaderAlias("shebeiChengben", "设备成本");
        writer.addHeaderAlias("chengben", "产品成本");
        writer.addHeaderAlias("facePrice", "面价");
        writer.addHeaderAlias("baojia", "报价");
        writer.addHeaderAlias("zhekou", "折扣");
        writer.addHeaderAlias("shijibaojia", "实际报价");
        writer.addHeaderAlias("proNum", "数量");
        writer.addHeaderAlias("allchengben", "总成本");
        writer.addHeaderAlias("allbaojia", "总报价");
        writer.addHeaderAlias("alllirun", "总利润");
        writer.addHeaderAlias("profit", "利润比");
        writer.addHeaderAlias("beizhu", "备注");


        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(22, sonsysDO.getProjectDO().getProjectNum() + "." + sonsysDO.getProjectDO().getProjectName()
                + " - " + sonsysDO.getSonsysName()
                + "  子系统成本：" + MyUtils.getAlldouble(sonsysDO.getSonchengben() )
                + "  子系统报价：" + MyUtils.getAlldouble(sonsysDO.getSonbaojia() )
                + "  子系统利润：" + MyUtils.getAlldouble(sonsysDO.getSonlirun()));
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(list, true);
        //out为OutputStream，需要写出到的目标流
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        String name = sonsysDO.getSonsysName();

        name = new String(name.getBytes("GBK"), "ISO8859_1");
        response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            writer.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer，释放内存
            writer.close();
        }
        //此处记得关闭输出Servlet流
        IoUtil.close(out);

    }

    @Autowired
    private CategoryService categoryService;


    public List<ProjectVo> getVoBydo(List<ProductInnerDO> productInnerList) {
        ArrayList<ProjectVo> projectVos = new ArrayList<>();

        for (ProductInnerDO productInnerDO : productInnerList) {
            ProjectVo projectVo = new ProjectVo();
            ProductDO productDO2 = productService.get(productInnerDO.getProductId());
            productInnerDO.setProductDO(productDO2);

            //
            BeanUtils.copyProperties(productInnerDO, projectVo);

            SonsysDO sonsysDO = sonsysService.get(productInnerDO.getSonsysId());
            productInnerDO.setSonsysDO(sonsysDO);

            CategoryDO categoryDO = categoryService.get(productDO2.getCategoryId());
            projectVo.setCategoryName(categoryDO.getCategoryName());

            BeanUtils.copyProperties(productDO2, projectVo);
            System.out.println("beabutil完了的商品vo="+projectVo);
            projectVo.setBrand(productDO2.getBrand());
            projectVo.setAllParam(productDO2.getAllParam());
            projectVo.setBaseParam(productDO2.getBaseParam());
            projectVo.setUnit(productDO2.getUnit());
            projectVo.setXinghao(productDO2.getXinghao());

            System.out.println("set完了的商品vo="+projectVo);

            projectVo.setShebeiName(productInnerDO.getProductDO().getShebeiName());
            projectVo.setAnzhuangChengben(productInnerDO.getProductDO().getAnzhuangChengben());
            projectVo.setShebeiChengben(productInnerDO.getProductDO().getShebeiChengben());
            projectVo.setChengben(productInnerDO.getProductDO().getChengben());
            projectVo.setFacePrice(productInnerDO.getProductDO().getFacePrice());
            projectVo.setSonsysName(productInnerDO.getSonsysDO().getSonsysName());
            projectVo.setCategoryName(categoryDO.getCategoryName());
            projectVos.add(projectVo);


        }

        return projectVos;
    }

    @GetMapping("/{projectId}")
    @RequiresPermissions("system:sonsys:sonsys")
    String Sonsys(@PathVariable("projectId") Integer projectId, Model model, HttpServletRequest request) {

        ProjectDO projectDO = projectService.get(projectId);

        model.addAttribute("project", projectDO);
        System.out.println("session的项目id=" + projectId);
        request.getSession().setAttribute("projectId", projectId);

        productInnerController.calall(request, projectId);

        return "system/sonsys/sonsys";
    }

    @ResponseBody
    @GetMapping("/list/{projectId}")
    @RequiresPermissions("system:sonsys:sonsys")
    public PageUtils list(@RequestParam Map<String, Object> params,
                          HttpServletRequest request, @PathVariable("projectId") Integer projectId) {

        String username = request.getSession().getAttribute("username").toString();
        UserDO userDo = userService.getUserByUsername(username);
        params.put("userId", userDo.getUserId());
        params.put("projectId", projectId);
        //查询列表数据
        Query query = new Query(params);
        List<SonsysDO> sonsysList = sonsysService.list(query);

        PageUtils pageUtils = new PageUtils(sonsysList, sonsysService.count(query));
        return pageUtils;
    }

    @GetMapping("/add/{projectId}")
    @RequiresPermissions("system:sonsys:add")
    String add(Model model, @PathVariable("projectId") Integer projectId) {

        ProjectDO projectDO = projectService.get(projectId);

        model.addAttribute("projectDO", projectDO);

        //setprojectlist(request);

        return "system/sonsys/add";
    }

    @GetMapping("/edit/{sonsysId}")
    @RequiresPermissions("system:sonsys:edit")
    String edit(@PathVariable("sonsysId") Integer sonsysId, Model model, HttpServletRequest request) {
        SonsysDO sonsys = sonsysService.get(sonsysId);
        model.addAttribute("sonsys", sonsys);
        setprojectlist(request);
        return "system/sonsys/edit";
    }

    public void setprojectlist(HttpServletRequest request) {
        String username = request.getSession().getAttribute("username").toString();
        UserDO userDo = userService.getUserByUsername(username);

        List<ProjectDO> projectList = projectService.listforchoose(userDo.getUserId());

        request.setAttribute("projectList", projectList);
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("system:sonsys:add")
    public R save(SonsysDO sonsys) {
        if (sonsysService.save(sonsys) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("system:sonsys:edit")
    public R update(SonsysDO sonsys) {
        sonsysService.update(sonsys);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("system:sonsys:remove")
    public R remove(Integer sonsysId) {
        if (sonsysService.remove(sonsysId) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("system:sonsys:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] sonsysIds) {
        sonsysService.batchRemove(sonsysIds);
        return R.ok();
    }

}
